package ${projectDomain}.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;

@Configuration
@Api(value="获取spring bean公共类", author="unswift", date="2023-05-05", version="1.0.0")
public class BeanUtils implements ApplicationContextAware{

	@ApiField("spring cloud 上下文对象")
	private static ApplicationContext applicationContext;
	
	@Override
	@ApiMethod(value="设置spring cloud 上下文对象", params=@ApiField("spring cloud 上下文对象"))
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		BeanUtils.applicationContext=applicationContext;
	}
	
	@ApiMethod(value="根据反射类类型获取bean", params=@ApiField("反射类类型"))
	public static <T> T getBean(Class<T> sourceClass){
		return applicationContext.getBean(sourceClass);
	}
	
	@SuppressWarnings("unchecked")
	@ApiMethod(value="根据bean名称获取bean", params=@ApiField("bean名称"))
	public static <T> T getBean(String beanName){
		return (T)applicationContext.getBean(beanName);
	}
	
	@ApiMethod(value="获取自动注入Bean工程", returns =@ApiField("自动注入Bean工厂"))
	public static AutowireCapableBeanFactory getAutowireCapableBeanFactory() {
		return applicationContext.getAutowireCapableBeanFactory();
	}
}
